﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AbpProjectTemplate.Web.Cors
{
    public static class CorsAspNetCoreExtensions
    {
        public const string CorsPolicyName = "AbpProjectTemplate";

        public static void AddAppCors(this IServiceCollection services, string[] origins) {
            services.AddTransient<ICorsService, WildcardCorsService>();
            // Configure CORS for angular2 UI
            //var origins = configuration.GetSection("Cors:Origins").Get<string[]>();
            services.AddCors(
                options => options.AddPolicy(
                    CorsPolicyName,
                    builder => builder
                        .WithOrigins(origins)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                )
            );
        }

        public static void UseAppCors(this IApplicationBuilder app) 
        {
            app.UseCors(CorsPolicyName); // Enable CORS!
        }
    }
}
